<template>
  <div class="h-full flex flex-col text-#fff justify-center relative">
    <!-- 设置菜单 -->
    <div class="fixed right-20px top-20px z-1000">
      <el-dropdown trigger="click" placement="bottom-end">
        <span class="el-dropdown-link cursor-pointer">
          <el-icon :size="20" color="#fff"><Setting /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="handleModelSettings">
              <el-icon><Cpu /></el-icon>
              大模型管理
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 大模型管理弹窗 -->
    <el-dialog
      v-model="modelManagementVisible"
      title="大模型管理"
      style="text-align: center"
      @resize="handleDialogResize"
    >
      <div class="flex justify-between mb-4">
        <h2>大模型列表</h2>
        <el-button type="primary" @click="handleAddModel">
          增加大模型
        </el-button>
      </div>
      <div class="model-table-container">
        <el-table
          :data="store.models"
          stripe
          class="model-table"
          :max-height="dialogHeight"
          style="width: 100%"
        >
          <el-table-column prop="id" label="模型id" v-show="false" />
          <el-table-column prop="name" label="模型名称" />
          <el-table-column prop="connectionType" label="连接类型" />
          <el-table-column prop="endpoint" label="请求网址" />
          <el-table-column prop="temperature" label="温度" />
          <el-table-column prop="top_p" label="top_p" />
          <el-table-column prop="max_tokens" label="最大令牌数" />
          <el-table-column prop="repetition_penalty" label="重复惩罚" />
          <el-table-column prop="top_k" label="top_k" />
          <el-table-column prop="min_p" label="min_p" />
          <el-table-column
            prop="operation"
            label="操作"
            fixed="right"
            width="220"
          >
            <template #default="{ row }">
              <div class="flex items-center gap-4">
                <el-button
                  size="small"
                  @click="handleEditModel(row)"
                  type="primary"
                  plain
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  @click="handleDeleteModel(row.id)"
                  type="danger"
                  plain
                >
                  删除
                </el-button>
                <el-button
                  size="small"
                  @click="handleCopyModel(row)"
                  type="info"
                  plain
                >
                  复制
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加/编辑大模型弹窗 -->
      <el-dialog
        v-model="modelFormVisible"
        :title="editing ? '编辑大模型' : '新增大模型'"
        width="500px"
        append-to-body
      >
        <el-form :model="modelForm" label-width="120px">
          <el-form-item label="模型id">
            <el-input v-model="modelForm.id" disabled />
          </el-form-item>
          <el-form-item label="模型名称">
            <el-input v-model="modelForm.name" />
          </el-form-item>
          <el-form-item label="连接类型" prop="connectionType">
            <el-select
              v-model="modelForm.connectionType"
              placeholder="请选择连接类型"
            >
              <el-option label="openApi" value="openApi"></el-option>
              <el-option label="ollama" value="ollama"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请求网址">
            <el-input v-model="modelForm.endpoint" />
          </el-form-item>
          <el-form-item label="请求API">
            <el-input v-model="modelForm.apiUrl" />
          </el-form-item>
          <el-form-item label="密钥">
            <el-input
              v-model="modelForm.secretKey"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="温度">
            <el-input
              v-model.number="modelForm.temperature"
              type="number"
              precision="2"
            />
          </el-form-item>
          <el-form-item label="top_p">
            <el-input
              v-model.number="modelForm.top_p"
              type="number"
              precision="2"
            />
          </el-form-item>
          <el-form-item label="最大令牌数">
            <el-input
              v-model.number="modelForm.max_tokens"
              type="number"
              precision="0"
            />
          </el-form-item>
          <el-form-item label="重复惩罚">
            <el-input
              v-model.number="modelForm.repetition_penalty"
              type="number"
              precision="2"
            />
          </el-form-item>
          <el-form-item label="top_k">
            <el-input
              v-model.number="modelForm.top_k"
              type="number"
              precision="0"
            />
          </el-form-item>
          <el-form-item label="min_p">
            <el-input
              v-model.number="modelForm.min_p"
              type="number"
              precision="2"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="modelFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitModel">
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>
    <div
      class="h-50px leading-50px text-20px text-center px-20px"
      v-if="dataSources.length"
    >
      {{ currentChatHistory?.title }}
    </div>
    <main class="overflow-hidden" :class="{ 'flex-1': dataSources.length }">
      <el-scrollbar ref="scrollRef">
        <div id="scroll-box" class="w-full max-w-screen-md m-auto">
          <div v-if="!dataSources.length" class="text-center p-20px">
            <div class="text-26px font-bold">我是 Mini Chat，很高兴见到你</div>
            <div class="text-14px mt-10px">
              除了可以帮你写代码、读文件、写作各种创意内容，还可以分析股票哦~
            </div>
          </div>
          <div v-else>
            <Message
              v-for="(item, index) of dataSources"
              :key="index"
              :date-time="item.dateTime"
              :text="item.text"
              :reasoning="item.reasoning"
              :inversion="item.inversion"
              :error="item.error"
              :loading="item.loading"
            />
            <!-- 在消息列表渲染完成后添加刷新按钮容器 -->
            <div class="refresh-button-container" v-if="dataSources.length > 0">
              <el-button
                type="primary"
                :icon="Refresh"
                :disabled="loading"
                @click="handleRefresh"
              >
                重试
              </el-button>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </main>
    <!-- 输入框 -->
    <footer>
      <div class="py-20px max-w-screen-md m-auto">
        <div class="p-15px bg-#404045 rounded-24px">
          <!-- 新增的联网查询开关 -->
          <div class="flex items-center mb-4">
            <el-switch
              v-model="isStockAnalysisEnabled"
              @change="handleIsStockAnalysisEnabled"
            />
            <span class="ml-2 text-#ccc">股票分析</span>

            <div
              v-if="isStockAnalysisEnabled"
              class="flex items-center ml-4 space-x-4"
            >
              <el-input
                v-model="stockCode"
                placeholder="股票代码"
                style="width: 120px"
              />
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 240px"
              />
            </div>
          </div>
          <div v-if="webSearchResult" class="mb-4 p-3 bg-#2d2d30 rounded-8px">
            <div class="text-sm text-#aaa mb-2">联网搜索结果：</div>
            <div class="text-sm text-#ccc">{{ webSearchResult }}</div>
          </div>
          <div class="input-box">
            <el-input
              v-model="prompt"
              style="width: 100%"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              resize="none"
              placeholder="发送消息"
              @keypress="handleEnter"
            />
          </div>
          <div class="flex items-center justify-between">
            <div></div>
            <div class="flex items-center">
              <!-- <el-button :icon="Link" circle /> -->
              <el-button
                v-if="loading"
                type="primary"
                :icon="CloseBold"
                circle
                @click="handleStop"
              />
              <el-button
                v-else
                type="primary"
                :icon="Position"
                :disabled="!prompt"
                circle
                @click="handleSubmit"
              />
            </div>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import {
  Position,
  CloseBold,
  Setting,
  Cpu,
  Refresh,
} from '@element-plus/icons-vue'
import Message from './components/Message/index.vue'
import { ElMessageBox } from 'element-plus'
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { chatCompletions, getStockData, webSearch } from '@/api/chat'
import { useChat } from './hooks/useChat'
import { useScroll } from './hooks/useScroll'
import { useChatStore } from '@/store/modules/chat'
import { useRoute } from 'vue-router'
import { useReadStream } from './hooks/useReadStream'
import { ss } from '@/utils/storage'
import { useModelStore } from '@/store/modules/modelStore'
import { start } from 'nprogress'
const store = useModelStore()
let controller = new AbortController()
const chatStore = useChatStore()
const route = useRoute()

// 会话方法
const { addChat, updateChat } = useChat()
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll()
const { handleStreamResponse } = useReadStream()
const { uuid } = route.params as { uuid: string }
// 输入框
const prompt = ref<string>('')
const loading = ref<boolean>(false)
const lastPrompt = ref<string>('') // 用于保留上次发送的消息内容ß
// 对话信息
const dataSources = computed(() => chatStore.getChatByUuid(+uuid))
const currentChatHistory = computed(
  () => chatStore.getChatHistoryByCurrentActive
)

// 是否开启多轮对话，开启后会带上之前的聊天信息
const usingContext = computed<boolean>(() => chatStore.usingContext)
// 大模型管理相关状态
const modelManagementVisible = ref(false)
const modelFormVisible = ref(false)
const editing = ref(false)
const modelForm = ref({
  id: '',
  name: '',
  endpoint: '',
  apiUrl: '',
  secretKey: '',
  temperature: 0.6,
  top_p: 0.95,
  max_tokens: 8192,
  repetition_penalty: 1.2,
  top_k: 30,
  min_p: 0,
  connectionType: '',
})
const dialogHeight = ref(500) // 初始高度
const isStockAnalysisEnabled = ref(false)
const stockCode = ref('')
const dateRange = ref<[Date, Date]>([new Date(), new Date()])
const webSearchResult = ref<string>('') // 存储联网搜索结果
// 输入框回车事件
function handleEnter(event: KeyboardEvent) {
  if (store.selectedModelId == null) {
    ElMessageBox.alert('请先选择或添加大模型', '未选择大模型', {
      confirmButtonText: '确定',
      type: 'warning',
    })
    return
  }
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleSubmit()
  }
}
async function handleSubmit() {
  // ✅ 股票分析模式处理
  if (isStockAnalysisEnabled.value && stockCode.value && dateRange.value) {
    const [startDate, endDate] = dateRange.value.map(
      (date) => date.toISOString().split('T')[0]
    )

    try {
      let targetUuid = +uuid
      let newUuid = 0
      // 🔁 显示加载状态
      if (!targetUuid || targetUuid === 0) {
        newUuid = Date.now()
        addChat(+newUuid, {
          dateTime: new Date().toLocaleString(),
          text: '',
          reasoning: `正在获取 ${stockCode.value}（${startDate} 至 ${endDate}）数据...`,
          loading: true,
          inversion: false,
          error: false,
        })
      } else {
        addChat(+targetUuid, {
          dateTime: new Date().toLocaleString(),
          text: '',
          reasoning: `正在获取 ${stockCode.value}（${startDate} 至 ${endDate}）数据...`,
          loading: true,
          inversion: false,
          error: false,
        })
      }
      scrollToBottom()
      // 📊 请求股票数据
      // const response = await axios.get('/api/stock-data', {
      //   params: {
      //     code: stockCode.value,
      //     start: startDate,
      //     end: endDate
      //   }
      // })
      const response = await getStockData(
        stockCode.value,
        startDate.replace(/-/g, ''),
        endDate.replace(/-/g, '')
      )
      const stockDataList = response.data.data.data
      const stockDataBasic = response.data.data.metadata
      let searchContent = ''
      try {
        const searchResponse = await webSearch(stockCode.value, prompt.value)
        searchContent = searchResponse.data.results
        webSearchResult.value = searchContent // 在页面上显示搜索结果
      } catch (error) {
        console.error('联网搜索失败:', error)
        webSearchResult.value = '联网搜索失败，请稍后重试'
      }

      // 🧠 构造提示词
      const analysisPrompt = generateStockAnalysisPrompt(
        stockDataList,
        stockDataBasic,
        prompt.value,
        searchContent // 传递联网搜索内容
      )
      prompt.value = analysisPrompt
      if (!+uuid || +uuid === 0) {
        chatStore.addHistory({
          title: '新建会话',
          uuid: newUuid,
          isEdit: false,
          visible: false,
        })
        ss.set('chatSubmitPrompt', prompt.value)
        return
      }
      // 🔄 替换原始提示词
      // lastPrompt.value = prompt.value
    } catch (error) {
      loading.value = false
      return
    }
  } else {
    if (!+uuid || +uuid === 0) {
      chatStore.addHistory({
        title: '新建会话',
        uuid: Date.now(),
        isEdit: false,
        visible: false,
      })
      ss.set('chatSubmitPrompt', prompt.value)
      return
    }
  }
  onConversation()
}
function formatNumber(num: number) {
  if (num >= 100000000) {
    return (num / 100000000).toFixed(2) + '亿'
  }
  if (num >= 10000) {
    return (num / 10000).toFixed(2) + '万'
  }
  return num.toFixed(2)
}

function generateStockAnalysisPrompt(
  data: any,
  basicData: string,
  value: string,
  webSearchContent: string
): string {
  const latest = data[data.length - 1]
  const timeRange = `${data[0].日期} 至 ${latest.日期}`
  let result = ''
  const basicDataItem = basicData
  const gpdm = basicDataItem.股票代码
  const gpmc = basicDataItem.股票名称
  const jlr =
    basicDataItem.净利润 !== '-' ? formatNumber(basicDataItem.净利润) : ''
  const zsz = formatNumber(basicDataItem.总市值)
  const ltsz = formatNumber(basicDataItem.流通市值)
  const schy = basicDataItem.所处行业
  const dtsyl =
    basicDataItem.动态市盈率 !== '-' ? basicDataItem.动态市盈率.toFixed(2) : ''
  const sjl =
    basicDataItem.市净率 !== '-' ? basicDataItem.市净率.toFixed(2) : ''
  const jll =
    basicDataItem.净利率 !== '-' ? basicDataItem.净利率.toFixed(2) : ''
  const mll =
    basicDataItem.毛利率 !== '-' ? basicDataItem.毛利率.toFixed(2) : ''
  const roe = basicDataItem.ROE !== '-' ? basicDataItem.ROE.toFixed(2) : ''

  result = `
  📊 基本面：
    - 股票代码：${gpdm}
    - 股票名称：${gpmc}
    - 净利润：${jlr}
    - 总市值：${zsz}
    - 流通市值：${ltsz}
    - 所处行业：${schy}
    - 市盈率(动)：${dtsyl}
    - 市净率：${sjl}
    - ROE：${roe}
    - 净利率：${jll}
    - 毛利率：${mll}

  `
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    const kaipan = item.开盘 === null ? '' : item.开盘.toFixed(2)
    const shoupan = item.收盘 === null ? '' : item.收盘.toFixed(2)
    const zhangdiefu = item.涨跌幅 === null ? '' : item.涨跌幅
    const zhangdiee = item.涨跌额 === null ? '' : item.涨跌额
    const chengjiaoliang =
      item.成交量 === null ? '' : item.成交量.toLocaleString()
    const huanshoulv = item.换手率 === null ? '' : item.换手率
    const zuigao = item.最高 === null ? '' : item.最高
    const zuidi = item.最低 === null ? '' : item.最低
    const rsi = item.RSI === null ? '' : item.RSI.toFixed(2)
    const k = item.K === null ? '' : item.K.toFixed(2)
    const d = item.D === null ? '' : item.D.toFixed(2)
    const j = item.J === null ? '' : item.J.toFixed(2)
    const cddjlr = item.超大单净流入 === null ? '' : item.超大单净流入
    const cddjlrzb = item.超大单流入净占比 === null ? '' : item.超大单流入净占比
    const ddlr = item.大单净流入 === null ? '' : item.大单净流入
    const ddlrzb = item.大单流入净占比 === null ? '' : item.大单流入净占比
    const zdjlr = item.中单净流入 === null ? '' : item.中单净流入
    const zdlrzb = item.中单流入净占比 === null ? '' : item.中单流入净占比
    const xdjlr = item.小单净流入 === null ? '' : item.小单净流入
    const xdlrzb = item.小单流入净占比 === null ? '' : item.小单流入净占比
    const dif = item.DIF === null ? '' : item.DIF.toFixed(4)
    const dea = item.DEA === null ? '' : item.DEA.toFixed(4)
    const macd = item.MACD === null ? '' : item.MACD.toFixed(4)
    const ma5 = item.MA5 === null ? '' : item.MA5.toFixed(2)
    const ma10 = item.MA10 === null ? '' : item.MA10.toFixed(2)
    const ma20 = item.MA20 === null ? '' : item.MA20.toFixed(2)
    const ma30 = item.MA30 === null ? '' : item.MA30.toFixed(2)
    // const macd = item.MACD === null ? '' : item.MACD.toFixed(2)
    if (gpdm == '000001' || gpdm == '399001' || gpdm == '399006') {
      result += `
    📊 每日行情：
    - 日期：${data[i].日期}
    - 开盘点数：${kaipan}
    - 收盘点数：${shoupan}
    - 涨跌幅：${zhangdiefu}%（${zhangdiee}点）
    - 成交量：${chengjiaoliang}手
    - 换手率：${huanshoulv}%
    - 最高点数：${zuigao}
    - 最低点数：${zuidi}
    - 超大单净流入: ${cddjlr}元
    - 超大单净流入占比: ${cddjlrzb}
    - 大单净流入: ${ddlr}元
    - 大单净流入占比: ${ddlrzb}
    - 中单净流入: ${zdjlr}元
    - 中单净流入占比: ${zdlrzb}
    - 小单净流入: ${xdjlr}元
    - 小单净流入占比: ${xdlrzb}
    📈 关键技术指标：ß
    - RSI：${rsi}
    - KDJ：K=${k}，D=${d}，J=${j}
    - MACD:macd=${macd}，dif=${dif}，dea=${dea}
    - 均线:5日=${ma5}，10日=${ma10}，20日=${ma20}，30日=${ma30}
    `
    } else {
      result += `
    📊 每日行情：
    - 日期：${data[i].日期}
    - 开盘价：${kaipan}元
    - 收盘价：${shoupan}元
    - 涨跌幅：${zhangdiefu}%（${zhangdiee}元）
    - 成交量：${chengjiaoliang}手
    - 换手率：${huanshoulv}%
    - 最高：${zuigao}元
    - 最低：${zuidi}元
    - 超大单净流入: ${cddjlr}元
    - 超大单净流入占比: ${cddjlrzb}
    - 大单净流入: ${ddlr}元
    - 大单净流入占比: ${ddlrzb}
    - 中单净流入: ${zdjlr}元
    - 中单净流入占比: ${zdlrzb}
    - 小单净流入: ${xdjlr}元
    - 小单净流入占比: ${xdlrzb}
    📈 关键技术指标：
    - RSI：${rsi}
    - KDJ：K=${k}，D=${d}，J=${j}
    - MACD:macd=${macd}，dif=${dif}，dea=${dea}
    - 均线:5日=${ma5}，10日=${ma10}，20日=${ma20}，30日=${ma30}
    `
    }
  }
  // 添加联网搜索内容到提示词中
  if (webSearchContent) {
    result += `
    
🔍 最新市场动态和新闻：
${webSearchContent}
`
  }
  return `
你是一个专业的股票分析师，基于以下${data[0].股票代码}（${data[0].股票名称}）在 ${timeRange} 的结构化数据来分析判断，不需要过程直接给出结果
分两步回答：
1. 识别当前趋势特征（如动量、波动性）。
2. 建议未来3日的操作策略（买入/卖出/持有），以及买入以及卖出的位置。

${result}

补充内容:${value}
`
}

async function onConversation() {
  lastPrompt.value = prompt.value // 记录上次发送的消息内容
  let message = prompt.value
  if (loading.value) return
  if (!message || message.trim() === '') return
  // 流式输出信号
  controller = new AbortController()
  const conversationList = dataSources.value
    .filter((item) => item.text)
    .map(
      (item) =>
        ({
          role: item.inversion ? 'user' : 'assistant',
          content: item.text,
        } as Chat.ConversationMessage)
    )
  // 添加用户消息到对话框
  addChat(+uuid, {
    dateTime: new Date().toLocaleString(),
    text: message,
    inversion: true,
    error: false,
  })
  scrollToBottom()
  loading.value = true
  prompt.value = ''
  // 添加AI初始对话 思考信息
  addChat(+uuid, {
    dateTime: new Date().toLocaleString(),
    text: '',
    reasoning: '思考中...',
    loading: true,
    inversion: false,
    error: false,
  })
  scrollToBottom()
  // 开始发起请求
  try {
    const paramMsg = []
    let contentText: any
    let reasoning: any
    let selectedModelJson: any
    if (usingContext.value) {
      // AI回复
      paramMsg.push(...conversationList)
    }
    paramMsg.push({ role: 'user', content: message })
    const response: any = await chatCompletions(controller.signal, paramMsg)
    await handleStreamResponse(response, (jsonData: any) => {
      let selectedModel = localStorage.getItem('selectedModel')
      if (selectedModel) {
        selectedModelJson = JSON.parse(selectedModel)

        if (selectedModelJson.connectionType === 'openApi') {
          contentText = jsonData.choices[0]?.delta?.content
        } else if (selectedModelJson.connectionType === 'ollama') {
          contentText = jsonData.message.content
        }
      }

      // const contentText = jsonData.message.content
      if (contentText) {
        updateChat(+uuid, dataSources.value.length - 1, {
          text: contentText ?? '',
          inversion: false,
          error: false,
          loading: true,
        })
        scrollToBottomIfAtBottom()
      }
      // 思考信息
      if (selectedModel) {
        if (selectedModelJson.connectionType === 'openApi') {
          reasoning = jsonData.choices[0].delta.reasoning_content
        } else if (selectedModelJson.connectionType === 'ollama') {
          reasoning = jsonData.message.reasoning_content
        }
      }
      // let reasoning = jsonData.choices[0].delta.reasoning_content
      // const reasoning = jsonData.message.reasoning_content
      if (reasoning) {
        updateChat(+uuid, dataSources.value.length - 1, {
          reasoning: reasoning ?? '',
          reasoningTime: new Date().toLocaleString(),
          inversion: false,
          error: false,
          loading: true,
        })
        scrollToBottomIfAtBottom()
      }
    })
    updateChat(+uuid, dataSources.value.length - 1, {
      inversion: false,
      error: false,
      loading: false,
    })
    loading.value = false
    console.log('Stream ended')
  } catch (error: any) {
    console.log(error)
    loading.value = false
    if (error instanceof DOMException && error.name === 'AbortError') {
      updateChat(+uuid, dataSources.value.length - 1, {
        text: '\n\n用户手动中断。',
        inversion: false,
        error: false,
        loading: false,
      })
    } else {
      updateChat(+uuid, dataSources.value.length - 1, {
        text: '\n\n服务器异常，请稍后再试。',
        inversion: false,
        error: true,
        loading: false,
      })
    }
  }
}

function handleIsStockAnalysisEnabled(value: any) {
  isStockAnalysisEnabled.value = value ? true : false
}
function handleStop() {
  if (loading.value) {
    controller.abort()
    loading.value = false
  }
}
onMounted(() => {
  console.log('onMounted', prompt.value)
  if (!route.params.uuid) {
    chatStore.active = 1002
  }
  const promptValue = ss.get('chatSubmitPrompt')
  if (promptValue) {
    prompt.value = promptValue
    ss.set('chatSubmitPrompt', '')
    onConversation()
  }
  scrollToBottom()
})
onUnmounted(() => {
  console.log('onUnmounted')
  if (loading.value) controller.abort()
})

// 大模型管理相关方法
function handleModelSettings() {
  store.loadModels()
  modelManagementVisible.value = true
}

function handleAddModel() {
  editing.value = false
  modelForm.value = {
    id: '',
    name: '',
    endpoint: '',
    apiUrl: '',
    secretKey: '',
    temperature: 0.4,
    top_p: 0.95,
    max_tokens: 8192,
    repetition_penalty: 1.2,
    top_k: 30,
    min_p: 0.1,
    connectionType: '',
  }
  modelFormVisible.value = true
}

function handleEditModel(row: {
  id: any
  name: any
  endpoint: any
  apiUrl: any
  secretKey: any
  temperature: any
  top_p: any
  max_tokens: any
  repetition_penalty: any
  top_k: any
  min_p: any
  connectionType: any
}) {
  editing.value = true
  modelForm.value = {
    id: row.id,
    name: row.name,
    endpoint: row.endpoint,
    apiUrl: row.apiUrl,
    secretKey: row.secretKey,
    temperature: row.temperature,
    top_p: row.top_p,
    max_tokens: row.max_tokens,
    repetition_penalty: row.repetition_penalty,
    top_k: row.top_k,
    min_p: row.min_p,
    connectionType: row.connectionType,
  }
  modelFormVisible.value = true
}

function handleDeleteModel(id: string) {
  store.deleteModel(id)
}
function handleCopyModel(row: any) {
  const newId = Date.now().toString()
  const newModel = {
    ...row,
    id: newId,
    name: `${row.name} - 副本`,
  }
  store.addModel(newModel)
}
function handleSubmitModel() {
  const validateParams = () => {
    const params = modelForm.value
    const regex = /^\d+\.?\d{0,2}$/

    if (!regex.test(params.temperature)) return '温度参数格式不正确'
    if (!regex.test(params.top_p)) return 'top_p格式不正确'
    if (!/^\d+$/.test(params.max_tokens)) return 'max_tokens必须为整数'
    if (!regex.test(params.repetition_penalty)) return '重复惩罚格式不正确'
    if (!/^\d+$/.test(params.top_k)) return 'top_k必须为整数'
    if (!regex.test(params.min_p)) return 'min_p格式不正确'

    return true
  }
  const validateResult = validateParams()
  if (validateResult !== true) {
    ElMessageBox.alert(validateResult, '参数校验失败', {
      confirmButtonText: '确定',
      type: 'error',
    })
    return
  }
  if (editing.value) {
    store.updateModel(modelForm.value)
  } else {
    store.addModel(modelForm.value)
  }
  modelFormVisible.value = false
}
function handleRefresh() {
  loading.value = false
  controller = new AbortController()

  // 恢复上次的消息内容
  prompt.value = lastPrompt.value

  // 清除旧的AI回复，仅保留用户消息
  const newDataSource = dataSources.value.filter(
    (item) => item.inversion === true
  )
  chatStore.setDataSources(+uuid, newDataSource)

  // 重新发送请求
  onConversation()
}
function handleDialogResize() {
  dialogHeight.value = window.innerHeight - 200 // 根据实际情况调整高度
}
</script>

<style scoped lang="scss">
.input-box {
  :deep(.el-textarea) {
    .el-textarea__inner {
      background-color: transparent;
      color: #fff;
      box-shadow: none;
      padding: 0;
      font-size: 16px;
    }
  }
}

/* 确保图标可见 */
.el-icon {
  vertical-align: middle; /* 修复图标对齐问题 */
}

/* 刷新按钮样式 */
.refresh-button-container {
  margin-top: 10px;
  text-align: left;

  .el-button {
    padding: 8px 16px;
    border-radius: 4px;
    background-color: #409eff;
    color: #fff;
    border: none;
    cursor: pointer;

    &:disabled {
      background-color: #a0cfff;
      cursor: not-allowed;
    }
  }
}

/* 消息列表布局 */
#scroll-box {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.el-input.is-readonly .el-input__inner {
  background-color: #35373b; /* 设置你想要的灰色背景 */
}

.model-table-container {
  overflow-x: hidden;
  width: 100%;
}

.model-table {
  min-width: auto; // 设置表格最小宽度，确保所有列可见
  width: 100%;
}
.el-table__fixed-right {
  height: 100% !important;
}
.el-table__body {
  overflow: visible;
}
.text-#ccc {
  color: #ccc;
}
</style>
